let Vue = null;
const install = (_Vue) => {
  Vue = _Vue;
  Vue.mixin({
    //  利用全局混入和 beforeCreate钩子函数实现了 给每一个组件上边都挂在了一个$store
    beforeCreate() {
      // console.log(this)
      // if(this.$parent){

      // }
      if (this.$options.store) {
        this.$store = this.$options.store
      } else if (this.$parent) {
        // 如存在 $parent证明当前组件时根组件的后代组件
        this.$store = this.$parent.$store
      }
      console.log(this)
    },
  })
}
class Store {
  constructor(options) {
    // options : state  ,mutations  actions
    // this.state = options.state
    let vm = new Vue({
      data() {
        return {
          state: options.state
        }
      },
    })
    this.state = vm.state;
    // this.mutations = options.mutations;
    this.mutations = {};
    let mutations = options.mutations || {};
    Object.keys(mutations).forEach(key => {
      this.mutations[key] = (option) => {
        mutations[key].call(this, this.state, option)
      }
    })
  }
  commit(type, option) {
    //  type 对应的时 mutations中的函数的名字  option使用户传递的参数
    this.mutations[type](option)
  }
}

export function mapState(ary) {
  let obj = {};
  ary.forEach(key => {
    obj[key] = function () {
      // this 时组建的实例
      console.log("组件实例：", this)
      return this.$store.state[key]
    }
  })
  return obj;
}
export function mapMutations(ary) {
  let obj = {};
  ary.forEach(key => {
    obj[key] = function (n) {
      this.$store.commit(key, n)
    }
  })
  return obj;
}

export default {
  install,
  Store
}